<template>

  <div class="mine">

    <!-- 顶部导航栏 -->

    <div v-if="show === 2">

      <div class="user-header">

        <!-- 用户信息区域 -->

        <div class="user-card">

          <van-image

              round

              width="60"

              height="60"

              :src="one.userimg"

              class="user-image"

          />

          <div class="user-details" @click="goToUserInfo">

            <div class="username">{{ one.username }}</div>

            <div class="user-type" v-if="this.one.isvip===1"><b style="color: #a58032">vip</b> 用户</div>
            <div class="user-type" v-if="this.one.isvip===0">普通用户</div>


          </div>

<!--          <div class="settings">-->

<!--            <van-icon name="chat-o" badge="1" class="message-icon" />-->

<!--            <van-icon name="setting-o" class="setting-icon" />-->

<!--          </div>-->

        </div>



        <!-- 货币信息卡片 -->

        <div class="currency-cards">

          <div class="currency-card yellow" @click="toRecharge()">

            <div class="amount">{{one.userglod1}}</div>

            <div class="label">汪汪币</div>

            <van-button size="small" type="default" class="action-btn">去充值</van-button>

          </div>

          <div class="currency-card pink">

            <div class="amount">{{one.userglod2}}</div>

            <div class="label">汪汪粮</div>

            <van-button size="small" type="default" class="action-btn" @click="exchangeGlod()">兑换汪汪币</van-button>

          </div>

        </div>



        <!-- 积分信息 -->

        <div class="points-info">

          <div class="points-row">

            <span>我的邀请码：{{one.invitation}} </span>

            <van-icon name="copy" color="#00b386" />

          </div>

          <div class="points-row">

            <span class="sub-text">兑换比例：10000汪汪粮=1汪汪币</span>

          </div>

          <div class="points-tabs">

            <div class="tab" @click="toBill">充值账单</div>

            <div class="tab" @click="goToWritereview">我的书评</div>

            <div class="tab" @click="goToFriends">我的好友</div>

          </div>

        </div>



        <!-- 功能列表 -->

        <div class="function-grid">

          <div class="grid-item" @click="toConsumption">
            <van-icon name="balance-list-o" color="#00b386" />
            <span>消费记录</span>
          </div>


          <div class="grid-item" @click="showInviteDialog">

            <van-icon name="scan" color="#00b386" />

            <span>输入邀请码</span>

          </div>

          <div class="grid-item" @click="goToWritereview">

            <van-icon name="comment-o" color="#00b386" />

            <span>我的书评</span>

          </div>

          <div class="grid-item" @click="goToFriends">

            <van-icon name="friends-o" color="#00b386" />

            <span>所有朋友</span>

          </div>

          <div class="grid-item" @click="help">

            <van-icon name="question-o" color="#00b386" />

            <span>帮助</span>

          </div>

        </div>



        <!--广告盒子-->
        <div class="ad-box" v-if="!one.isvip">
          <h5 style="background-color: #f0f0f0; padding: 10px; margin-top: 20px;">购买汪汪VIP享受纯净阅读体验！</h5>
          <div class="big-box">
            <div
                v-for="(banner, index) in bannerList.filter(item => item.picture)"
                :key="index"
                class="small-box"
            >
              <img :src="banner.picture" class="small-box-img" />
              <!-- 动态绑定 href 到 banner.url，文字限制为 15 个字 -->
              <p class="small-box-title">
                <a :href="banner.url" target="_blank">{{ banner.name.length > 15 ? banner.name.slice(0, 15) + '...' : banner.name }}</a>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 未登录状态 -->

    <div v-else class="login-prompt" v-if="show === 1">

      <!-- 未登录界面代码保持不变 -->

      <div class="login-info">

        <van-image
            round
            width="60"
            height="60"
            src="https://zhengfeixiang.oss-cn-beijing.aliyuncs.com/user/2024/12/22/e19aaf0892974d5dafe01304d18d930c.jpg"
        />
        <div class="login-text">
          <p>未登录</p>
          <van-button type="primary" @click="goToLogin">登录</van-button>
        </div>
      </div>
    </div>
    <!-- 底部导航栏 -->
    <van-tabbar v-model="activeTabbar" route>
      <van-tabbar-item icon="home-o" to="/">首页</van-tabbar-item>
      <van-tabbar-item icon="records" to="/task">任务</van-tabbar-item>
      <van-tabbar-item icon="bookmark-o" to="/bookshelf">书架</van-tabbar-item>
      <van-tabbar-item icon="user-o" to="/mine">我的</van-tabbar-item>
    </van-tabbar>



    <!-- 保留邀请码对话框 -->
    <van-dialog v-model="inviteDialogVisible" title="输入邀请码" @confirm="submitInvite">
      <van-field v-model="inviteCode" placeholder="请输入邀请码" />
      <template #footer>
        <div v-if="hasSubmittedInvite" style="color: red; text-align: center;">您已经输入过邀请码。</div>
      </template>
    </van-dialog>
  </div>
</template>



<script>
import axios from "axios";
export default {
  name: 'MineView',

  data() {

    return {

      id: "",

      user: {},

      todayCoins: "123,200", // 示例数据

      totalCoins: "200,356,100", // 示例数据

      activeTabbar: 4,

      userstatus: 0, // 默认状态为未登录

      inviteDialogVisible: false, // 控制对话框显示

      inviteCode: "", // 存储邀请码

      hasSubmittedInvite: false, // 控制是否已提交邀请码

      one: {},

      show: true,

      bannerList: [], // 广告列表

      currentAdIndex: 0, // 当前显示广告的索引

      defaultPicture: 'https://via.placeholder.com/150', // 默认占位图片

    }

  },

  created() {

    this.user = JSON.parse(localStorage.getItem("user"))

    if (this.user == null) {

      this.show = 1;

    } else {

      this.show = 2;

      this.fetchUserData();

      // alert(this.userphone)

      this.findOneUser();

      this.findAllExpenses();

    }

    this.banner();



  },
  watch:{
    allExpenses:{
      handler(newValue, oldValue) {
        if (this.allExpenses.length>0){
          this.updateIsvip();
        }
      },
    }
  },

  methods: {
    updateIsvip(){
      if (this.allExpenses[2]>=50000){
        axios.post("http://localhost:9999/api-user/user/updateVip?id="+this.user.id).then(res=>{
          console.log("修改了vip")
        })
      }else{
        console.log("普通用户")
      }
    },
    findAllExpenses(){
      axios.post("http://localhost:9999/api-user/recharge/findAllExpenses?id="+this.user.id).then(res=>{
        this.expenses = res.data;
        console.log(this.expenses)
        this.allExpenses = this.expenses.split(",");
      })
    },
    toConsumption(){
      this.$router.push("/consumption")
    },
    goToWritereview(){

      this.$router.push("/bookreview")

    },

    toBill() {

      this.$router.push("/bill")

    },

    exchangeGlod() {

      this.$router.push("/exchangeGlod")

    },

    toRecharge() {

      this.$router.push("/recharge")

    },

    findOneUser() {

      axios.post("http://localhost:9999/api-user/user/findOneUser?id=" + this.user.id).then(res => {
        this.one = res.data;
      })

    },

    fetchUserData() {

      axios.post("http://localhost:9999/api-user/user/find?id=" + this.user.id).then(res => {
        // alert(JSON.stringify(res.data.data))
        if (res.data.data && res.data.data.length > 0) {
          this.userstatus = res.data.data[0].userstatus; // 用户已登录
          this.username = res.data.data[0].username;
          this.invitation = res.data.data[0].invitation;
          this.userglod1 = res.data.data[0].userglod1;
          this.userimg = res.data.data[0].userimg;
          this.userphone = res.data.data[0].userphone;
          // location.reload(); // 刷新页面
        } else {

          this.userstatus = 0; // 用户未登录

        }

      }).catch(error => {

        this.$toast.fail("请求失败，请刷新重试。");

      });

    },

    goToFriends() {

      this.$router.push({path: "/friend", query: {id: this.id}})

    },

    help() {

      this.$router.push('/help');

    },

    // checkLoginStatus(phone) {

    //   axios.post("http://localhost:9999/api-user/user/find?userphone="+phone).then(res => {

    //     alert(res.data.data)

    //     if (res.data.data && res.data.data.length > 0) {

    //       this.userstatus = res.data.data[0].userstatus; // 用户已登录

    //       this.username = res.data.data[0].username;

    //       this.invitation = res.data.data[0].invitation;

    //       this.userglod1 = res.data.data[0].userglod1;

    //       this.userimg = res.data.data[0].userimg;

    //     } else {

    //       this.userstatus = 0; // 用户未登录

    //     }

    //   }).catch(error => {

    //     console.error("请求失败:", error);

    //     alert("请求失败，请检查控制台以获取更多信息。");

    //   });

    // },

    goToLogin() {

      this.$router.push('/login'); // 跳转到登录页面

    },

    goToUserInfo() {

      // this.$router.push('/userInfo'); // 跳转到用户信息页面

      // alert("userphone"+this.userphone)

      this.$router.push({path: '/userInfo', query: {id: this.user.id}});



    },

    showInviteDialog() {

      this.inviteDialogVisible = true; // 显示对话框

      this.inviteCode = ""; // 清空邀请码输入框

    },

    submitInvite() {

      if (this.hasSubmittedInvite) {

        this.$toast.fail("您已经输入过邀请码。");

        return; // 如果已经输入过邀请码，直接返回

      }



      axios.post("http://localhost:9999/api-user/user/invitation?invitation=" + this.inviteCode + "&id=" + this.user.id).then(res => {

        if (res.data.code === 1) {

          this.$toast.success("邀请成功");

          this.hasSubmittedInvite = true; // 设置为已提交

        } else {

          this.$toast.fail(res.data.message);

        }

      }).catch(error => {

        this.$toast.fail("请求失败，请刷新重试。");

      });



      console.log("提交的邀请码:", this.inviteCode);

      this.inviteDialogVisible = false; // 关闭对话框

      this.inviteCode = ""; // 清空邀请码

    },



    // 请求广告数据

    banner() {

      this.axios

          .post("http://localhost:9999/api-tagclass-service/banner/list")

          .then((res) => {

            this.bannerList = res.data;

          })

          .catch((error) => {

            console.error("请求失败:", error);

          });

    },

  }

}

</script>



<style scoped>

.banner {

  height: 200px;

  margin-bottom: 15px;

}



.banner-img {

  width: 100%;

  height: 100%;

  object-fit: cover;

}



.recommendations {

  padding: 0 15px;

}

.big-box {

  display: flex;

  flex-wrap: nowrap; /* 不换行，保持横排 */

  gap: 15px; /* 控制小盒子之间的间距 */

  justify-content: space-between; /* 小盒子等距分布 */

  overflow-x: auto; /* 超出部分滚动显示 */

}



.small-box {

  flex: 0 0 calc(25% - 10px); /* 每个小盒子固定宽度（可根据需要调整） */

  display: flex;

  flex-direction: column;

  align-items: center;

  background-color: #f9f9f9;

  border: 1px solid #e0e0e0;

  border-radius: 4px;

  padding: 10px;

  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

}

.small-box-img {

  width: 100%;

  height: 100px;

  object-fit: cover;

  border-radius: 4px;

  margin-bottom: 8px;

}



.small-box-title {

  font-size: 14px;

  color: #333;

  text-align: center;

  line-height: 1.5;

}

.mine {

  background-color: #f7f8fa;

  min-height: 100vh;

}



.user-header {

  padding: 16px;

}



.user-card {

  display: flex;

  align-items: center;

  background: linear-gradient(135deg, #f9f9f9, #f0f0f0);

  border-radius: 12px;

  padding: 16px;

  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  margin-bottom: 20px;

}



.user-image {

  border: 2px solid #ff6f61; /* 头像边框颜色 */

}



.user-details {

  flex: 1;

  margin-left: 12px;

}



.username {

  font-size: 20px;

  font-weight: bold;

  color: #333;

}



.user-type {

  font-size: 14px;

  color: #666;

}



.settings {

  display: flex;

  gap: 12px;

}



.currency-cards {

  display: flex;

  gap: 12px;

  margin: 16px;

}



.currency-card {

  flex: 1;

  padding: 16px;

  border-radius: 12px;

  text-align: center;

}



.currency-card.yellow {

  background-color: #fff5e6;

  border: 1px solid #ffd591;

}



.currency-card.pink {

  background-color: #fff0f6;

  border: 1px solid #ffadd2;

}



.amount {

  font-size: 24px;

  font-weight: bold;

  color: #333;

  margin-bottom: 8px;

}



.label {

  font-size: 14px;

  color: #666;

  margin-bottom: 12px;

}



.action-btn {

  width: 80%;

  border-radius: 16px;

}



.points-info {

  margin: 16px;

  background: #fff;

  padding: 16px;

  border-radius: 12px;

  box-shadow: 0 2px 8px rgba(0,0,0,0.05);

}



.points-row {

  display: flex;

  justify-content: space-between;

  align-items: center;

  margin-bottom: 8px;

}



.points-tabs {

  display: flex;

  justify-content: space-around;

  margin-top: 16px;

  border-top: 1px solid #eee;

  padding-top: 16px;

}



.tab {

  font-size: 14px;

  color: #666;

  padding: 8px 16px;

  cursor: pointer;

}



.function-grid {

  display: grid;

  grid-template-columns: repeat(4, 1fr);

  gap: 16px;

  padding: 16px;

  margin: 16px;

  background: #fff;

  border-radius: 12px;

  box-shadow: 0 2px 8px rgba(0,0,0,0.05);

}



.grid-item {

  display: flex;

  flex-direction: column;

  align-items: center;

  gap: 8px;

  cursor: pointer;

}



.grid-item span {

  font-size: 12px;

  color: #666;

}



/* 其他样式保持不变 */

</style>
